package com.towa.ninemanmorris;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.towa.ninemanmorris.R;

public class WelcomeActivity extends Activity {
	private DatabaseToWa db;
	private long gameId = -1;
	private Button startButton;
	private Button loadButton;
	private List<GameNameIdWrapper> data;
	private ArrayAdapter<GameNameIdWrapper> adapter;
	private EditText playerOneField;
	private EditText playerTwoField;
	private Button setPlayers;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		db = new DatabaseToWa(this);
		data = db.getGameList();
		if(data.size() == 0)
			db.saveGame(new GameStatusWrapper());
		
		adapter = new ArrayAdapter<GameNameIdWrapper>(
				this, android.R.layout.simple_spinner_item, data);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		Spinner loadSpinner = (Spinner) findViewById(R.id.spinnerLoad);
		loadSpinner.setAdapter(adapter);
		loadSpinner.setOnItemSelectedListener(spinnerListener);

		startButton = (Button) findViewById(R.id.buttonStart);
		startButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				start();
			}

		});

		loadButton = (Button) findViewById(R.id.buttonLoad);
		loadButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				load();
			}

		});
		
		
		playerOneField = (EditText) findViewById(R.id.playerOneField);
		playerTwoField = (EditText) findViewById(R.id.playerTwoField);
		
//        String string = prefs.getString("authentication", "n/a");
		
		setPlayers = (Button) findViewById(R.id.setPlayers);
		setPlayers.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				SharedPreferences prefs = PreferenceManager  
		                .getDefaultSharedPreferences(WelcomeActivity.this);
				Editor edit = prefs.edit();
				edit.putString("playerOne", playerOneField.getText().toString());
				edit.putString("playerTwo", playerTwoField.getText().toString());
				new Tasker().doInBackground("user::" + playerOneField.getText().toString() + "::" + prefs.getString("deviceId", ""));
				new Tasker().doInBackground("user::" + playerTwoField.getText().toString() + "::" + prefs.getString("deviceId", ""));
				edit.commit();
			}
		});
		

		register();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		db = new DatabaseToWa(this);
		data = db.getGameList();
		if(data.size() == 0)
			db.saveGame(new GameStatusWrapper());
		db.close();
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WelcomeActivity.this);
		
		adapter.notifyDataSetChanged();
		playerOneField.setText(prefs.getString("playerOne", ""));
		playerTwoField.setText(prefs.getString("playerTwo", ""));
	}

	OnItemSelectedListener spinnerListener = new OnItemSelectedListener() {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			GameNameIdWrapper gniw = (GameNameIdWrapper) parent
					.getItemAtPosition(pos);
			gameId = gniw.getId();
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}

	};
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
		if (item.getItemId() == R.id.highscoreItem) {
			Log.d("MenuItems", "highscore");
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			
			alert.setTitle("Highscore");
			alert.setMessage("Select player to show highscore");
	
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WelcomeActivity.this);
			
			alert.setPositiveButton(prefs.getString("playerOne", "ERRORRS"), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent intent = new Intent(WelcomeActivity.this, HighscoreActivity.class);
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WelcomeActivity.this);
					intent.putExtra("player", prefs.getString("playerOne", "ERRORRS"));
					startActivity(intent);
					dialog.dismiss();
				}
			});
			alert.setNegativeButton(prefs.getString("playerTwo", "Errors"), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButtons) {
					Intent intent = new Intent(WelcomeActivity.this, HighscoreActivity.class);
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WelcomeActivity.this);
					intent.putExtra("player", prefs.getString("playerTwo", "ERRORRS"));
					startActivity(intent);
					dialog.dismiss();
				}
				
			});
			alert.show();
			return true;
		} else if (item.getItemId() == R.id.saveGame) {
			Log.d("MenuItems", "save game");
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
	
			alert.setTitle("Save Game!");
			alert.setMessage("No game active");
	
			alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					dialog.dismiss();
				}
			});
			alert.show();
    	} else if (item.getItemId() == R.id.groupItem) {
    		Log.i("MenuItems", "Group");
    		AlertDialog.Builder alert = new AlertDialog.Builder(this);
    		
    		alert.setTitle("Groups");
    		alert.setMessage("Select player to group with to do stuff");
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WelcomeActivity.this);
    		
    		alert.setPositiveButton(prefs.getString("playerOne", "Errors"), new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(WelcomeActivity.this, GroupActivity.class);
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WelcomeActivity.this);
					intent.putExtra("player", prefs.getString("playerOne", "ERRORRS"));
					startActivity(intent);
					dialog.dismiss();
				}
			});
    		
    		alert.setNegativeButton(prefs.getString("playerTwo", "Errors"), new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(WelcomeActivity.this, GroupActivity.class);
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WelcomeActivity.this);
					intent.putExtra("player", prefs.getString("playerTwo", "ERRORRS"));
					startActivity(intent);
					dialog.dismiss();
				}
			});
    		alert.show();
    		return true;
    	}
    	return false;
    }

	private void start() {
		SharedPreferences settings = getSharedPreferences("NineMenMorris", MODE_PRIVATE); 
    	Editor editor = settings.edit();
    	editor.putLong("gameId", -1);
    	editor.commit();
    	
		Intent intent = new Intent(WelcomeActivity.this, NineManMorrisActivity.class);
		intent.putExtra("gameId", -1);
		startActivity(intent);
		db.close();
	}

	private void load() {
		if(gameId != -1){
			Intent intent = new Intent(WelcomeActivity.this, NineManMorrisActivity.class);
			intent.putExtra("gameId", gameId);
//			startActivity(intent);
			startActivity(intent);
			db.close();
		}
	}
	

	@Override
	public void onDestroy() {
		super.onDestroy();
		db.close();
	}
	
	private void register() {
    	Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
        registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
        registrationIntent.putExtra("sender", "towaapp@gmail.com");
        startService(registrationIntent);
        Log.i("c2dm", "hello");
	}
    
    public void register(View view) {
    	register();
    }
    
    private void unregister() {
    	Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
    	unregIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
    	startService(unregIntent);
    }
    
    public void showRegistrationId(View view) {  
        SharedPreferences prefs = PreferenceManager  
                .getDefaultSharedPreferences(this);  
        String string = prefs.getString("authentication", "n/a");  
        Toast.makeText(this, string, Toast.LENGTH_LONG).show();  
        Log.d("C2DM RegId", string);  
    }  
    
    public void showDeviceId(View view) {
    	SharedPreferences prefs = PreferenceManager  
                .getDefaultSharedPreferences(this);  
        String string = prefs.getString("deviceId", "n/a");  
        Toast.makeText(this, string, Toast.LENGTH_LONG).show();  
        Log.d("C2DM DeviceId", string);
    }
    
    @Override
    public void onNewIntent(Intent intent) {
    	Log.i("C2DM", intent.getAction().toString());
    }

}
